package org.ucas.faker.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.ucas.faker.web.dto.CarryDto;
import org.ucas.faker.web.dto.PageDto;
import org.ucas.faker.web.dto.ResponseDto;
import org.ucas.faker.web.entity.Query;
import org.ucas.faker.web.exceptions.ForbiddenException;
import org.ucas.faker.web.service.QueryService;

@RestController
@SuppressWarnings("unchecked")
public class QueryController extends BaseController {

  @Autowired
  private QueryService queryService;


  @RequestMapping(value = "/query/list", method = RequestMethod.POST)
  PageDto<Query> list(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                      @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
    Page<Query> page = queryService.page(currentUserId(),pageNumber,pageSize,1);
    return PageDto.of(page);
  }

  @RequestMapping(value = "/query/list/all", method = RequestMethod.POST)
  PageDto<Query> listAll(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                         @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
    Page<Query> page = queryService.page(currentUserId(),pageNumber,pageSize,null);
    return PageDto.of(page);
  }

  @RequestMapping(value = "/query/save", method = RequestMethod.POST)
  public CarryDto<Query> save(@RequestParam(value = "query", required = true) String query) {

    Query q = new Query(currentUserId(),query,1);
    queryService.create(q);
    return CarryDto.of(q);
  }

  @RequestMapping(value = "/query/delete", method = RequestMethod.POST)
  ResponseDto delete(@RequestParam(value = "id", required = true) Long id) {
	System.out.println("id..............."+id);
    Query query = queryService.load(id);
    if(query != null && !query.getUserId().equals(currentUserId()))
      throw ForbiddenException.FORBIDDEN;
    queryService.delete(id);
    return ResponseDto.OK;
  }
}
